package com.arvin.faceDetect.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.SeekBar
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.arvin.faceDetect.databinding.FragmentCollectionSettingsBinding
import com.arvin.faceDetect.utils.Settings
import com.google.mlkit.vision.face.FaceDetectorOptions

class CollectionSettingsFragment : Fragment() {

    private var _binding: FragmentCollectionSettingsBinding? = null
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentCollectionSettingsBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupToolbar()
        setupCollectionSettings()
        loadSettings()
    }

    private fun setupToolbar() {
        binding.toolbar.setNavigationOnClickListener {
            findNavController().navigateUp()
        }
    }

    private fun setupCollectionSettings() {
        // 设置性能模式选择
        binding.rgPerformanceMode.setOnCheckedChangeListener { _, checkedId ->
            val isAccurateMode = checkedId == binding.rbAccurateMode.id
            Settings.setCollectionPerformanceMode(
                requireContext(),
                if (isAccurateMode) FaceDetectorOptions.PERFORMANCE_MODE_ACCURATE
                else FaceDetectorOptions.PERFORMANCE_MODE_FAST
            )
        }

        // 设置最小人脸尺寸
        binding.sbMinFaceSize.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                val minFaceSize = (progress + 20) / 100f // 20-90%
                binding.tvMinFaceSize.text = "当前值: ${(minFaceSize * 100).toInt()}%"
                if (fromUser) {
                    Settings.setCollectionMinFaceSize(requireContext(), minFaceSize)
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {}
            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })

        // 设置最大人脸尺寸
        binding.sbMaxFaceSize.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                val maxFaceSize = (progress + 10) / 100f // 10-100%
                binding.tvMaxFaceSize.text = "当前值: ${(maxFaceSize * 100).toInt()}%"
                if (fromUser) {
                    Settings.setMaxFaceSize(requireContext(), maxFaceSize)
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {}
            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })

        // 设置采集所需帧数
        binding.sbRequiredFrames.setOnSeekBarChangeListener(object :
            SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                val frames = progress + 2 // 最少2帧
                binding.tvRequiredFrames.text = "当前值: ${frames}帧"
                if (fromUser) {
                    saveCollectionRequiredFrames(frames)
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {}
            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })

        // 设置采集阈值
        binding.sbCollectionThreshold.setOnSeekBarChangeListener(object :
            SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                val threshold = 0.80f + (progress / 100f) // 0.80-1.00
                binding.tvCollectionThreshold.text = "当前值: %.2f".format(threshold)
                if (fromUser) {
                    saveCollectionThreshold(threshold)
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {}
            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })

        binding.sbCollectionInterval.setOnSeekBarChangeListener(object :
            SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                val interval = progress + 1 // 最少1秒
                binding.tvCollectionInterval.text = "当前值: ${interval}秒"
                if (fromUser) {
                    saveCollectionInterval(interval)
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {}
            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })
    }

    private fun loadSettings() {
        // 加载性能模式设置
        val performanceMode = Settings.getCollectionPerformanceMode(requireContext())
        binding.rbAccurateMode.isChecked =
            performanceMode == FaceDetectorOptions.PERFORMANCE_MODE_ACCURATE
        binding.rbFastMode.isChecked = performanceMode == FaceDetectorOptions.PERFORMANCE_MODE_FAST

        // 加载最小人脸尺寸
        val minFaceSize = Settings.getCollectionMinFaceSize(requireContext())
        binding.sbMinFaceSize.progress = ((minFaceSize * 100) - 20).toInt()
        binding.tvMinFaceSize.text = "当前值: ${(minFaceSize * 100).toInt()}%"

        // 加载最大人脸尺寸
        val maxFaceSize = Settings.getMaxFaceSize(requireContext())
        binding.sbMaxFaceSize.progress = ((maxFaceSize * 100) - 10).toInt()
        binding.tvMaxFaceSize.text = "当前值: ${(maxFaceSize * 100).toInt()}%"

        // 加载采集所需帧数
        val requiredFrames = Settings.getCollectionRequiredFrames(requireContext())
        binding.sbRequiredFrames.progress = requiredFrames - 2
        binding.tvRequiredFrames.text = "当前值: ${requiredFrames}帧"

        // 加载采集阈值
        val threshold = Settings.getCollectionThreshold(requireContext())
        binding.sbCollectionThreshold.progress = ((threshold - 0.80f) * 100).toInt()
        binding.tvCollectionThreshold.text = "当前值: %.2f".format(threshold)

        // 加载采集间隔
        val interval = Settings.getCollectionInterval(requireContext())
        binding.sbCollectionInterval.progress = interval - 1
        binding.tvCollectionInterval.text = "当前值: ${interval}秒"
    }

    private fun saveCollectionRequiredFrames(frames: Int) {
        Settings.setCollectionRequiredFrames(requireContext(), frames)
    }

    private fun saveCollectionThreshold(threshold: Float) {
        Settings.setCollectionThreshold(requireContext(), threshold)
    }

    private fun saveCollectionInterval(interval: Int) {
        Settings.setCollectionInterval(requireContext(), interval)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
} 